<template>
  <div class="cqjc-chart" ref="chartDom">QW</div>
</template>
<script setup>
import { reactive, onMounted, watch, ref, toRaw } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  sourceData: {
    type: Object,
    default: () => {}
  }
})

const chartDom = ref(null)
let myChart
const echartsInit = () => {
  myChart = echarts.init(chartDom.value)
}
const echartsetOption = (param) => {
  let option = {
    color: [
      'rgba(233, 169, 14, 1)',
      'rgba(233, 246, 23, 1)',
      'rgba(5, 187, 112, 1)',
      'rgba(166, 72, 245, 1)',
      'rgba(38, 166, 255, 1)',
      'rgba(25, 241, 249, 1)',
      'rgba(217, 31, 79, 1)'
    ],
    legend: {
      show: param.length > 0,
      right: '0',
      orient: 'vertical',
      itemWidth: 4,
      itemHeight: 12,
      textStyle: {
        color: '#fff',
        fontSize: 10,
        rich: {
          name: {
            color: '#fff'
          },
          num: {
            color: '#fff',
            padding: [0, 10, 0, 4]
          },
          perce: {
            color: '#fff'
          }
        }
      },
      tooltip: {
        show: true
      },
      formatter: function (name) {
        let tarValue
        let perce
        if (param.length === 0) {
          return ''
        }
        const _total = param.reduce((a, b) => a + b.value, 0)
        for (var i = 0; i < param.length; i++) {
          if (param[i].name == name) {
            tarValue = param[i].value
            perce = ((param[i].value * 100) / _total).toFixed(1) + '%'
          }
        }
        return [`{name|${name}}{num|${tarValue}}{unit|${perce}}`]
      }
    },
    series: [
      {
        name: '虫情监测',
        left: 'left',
        type: 'pie',
        labelLine: {
          show: false
        },
        label: {
          show: true,
          position: 'center',
          color: '#fff',
          fontWeight: 'bold',
          formatter() {
            return '虫情监测'
          }
        },
        padAngle: 5,
        center: ['30%', '50%'],
        radius: ['70%', '90%'],
        data: param
      }
    ]
  }
  if (myChart) {
    myChart.setOption(option)
  }
}
onMounted(() => {
  echartsInit()
})

watch(
  () => props.sourceData,
  (newValue) => {
    const _newValue = toRaw(newValue)
    const _data = _newValue.map((item) => {
      return {
        name: item.name,
        value: item.num
      }
    })
    myChart && echartsetOption(_data)
  },
  {
    immediate: true
  }
)
</script>
<style lang="scss" scoped>
.cqjc-chart {
  width: 100%;
  height: 100%;
}
</style>
